<?php

namespace App\Http\Controllers;

use App\Models\Subject;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 公共相应方法
     * @param $code int 响应状态码
     * @param $message string 响应文本
     * @param $data mixed 相应数据
     * @return JsonResponse
     */
    public function baseResponse($code, $message, $data)
    {
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ]);
    }

    /**
     * 公共相应方法 - 成功
     * @param $message string 响应文本
     * @param $data mixed 响应数据
     * @return JsonResponse
     */
    public function success($message, $data)
    {
        return $this->baseResponse(0, $message, $data);
    }

    /**
     * 公共相应方法 - 失败
     * @param $message string 响应文本
     * @return JsonResponse
     */
    public function error($message)
    {
        return $this->baseResponse(1, $message, null);
    }

    /**
     * 保存
     * @param Request $request
     * @return JsonResponse
     */
    public function save(Request $request)
    {
        foreach ($request->get('subject') as $item) {
            if (isset($item['key']) && isset($item['value'])) {
                Subject::firstOrCreate([
                    'key'     => $item['key'],
                    'value'   => json_encode($item['value'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
                    'options' => json_encode($item['options'] ?? '', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
                ]);
            }
        }
        return $this->success("解析到服务器成功！", null);
    }

    /**
     * 查询题库
     * @param Request $request
     * @return JsonResponse
     */
    public function get(Request $request)
    {
        $keyword = $request->get('keyword');
        if (!$keyword) {
            return $this->error("关键字不存在");
        }
        $lists = Subject::query()->where("key", "like", "%$keyword%")->get();
        return $this->success("查询成功", $lists);
    }
}
